#!/usr/bin/python
# -*- encoding: utf-8 -*-

#   MusicLog Daemon
#
#   Copyright (c) 2008 Rafael G. Martins <rafael@rafaelmartins.com>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.

from mpd import MPDClient
from urllib import urlencode, urlopen
from time import sleep

class MusicLog:
  
  def __init__(self, mpd_host, mpd_port, wrapper_url, wrapper_pass=None):
    self.mpd_host     = mpd_host
    self.mpd_port     = mpd_port
    self.wrapper_url  = wrapper_url
    self.wrapper_pass = wrapper_pass
    self.client = MPDClient()
    self._connect(True)
  
  def _connect(self, init = False):
    while True:
      try:
        self.client.connect(self.mpd_host, self.mpd_port)
        return True
      except KeyboardInterrupt:
        return False
      except:
        if init == True:
          print "Musiclogd can't connect \"mpd\""
          exit()
        else:
          if self._sleep() == False:
            exit()
    return True

  def _sleep(self):
    try:
      sleep(0.2)
    except:
      return False
    return True

  def _time_percent(self):
    str = self.client.status();
    time = str["time"].split(":")
    current = float(time[0])
    total   = float(time[1])
    return (current/total) * 100

  def _is_playing(self):
    str = self.client.status();
    return (str["state"] == "play")

  def _do_request(self, song):
    if self.wrapper_pass != None:
      song["pass"] = self.wrapper_pass
    params = urlencode(song)
    try:
      urlopen(self.wrapper_url, params)
    except:
      #TODO: HTTP error log
      pass

  def update(self):
    aux = 100
    while True:
      try:
        if self._is_playing():
          percent = self._time_percent()
          if aux > percent:
            song = self.client.currentsong()
            self._do_request(song)
          aux = percent
        if self._sleep() == False:
          break
      except:
        try:
          self.client.disconnect()
        except:
          pass
        if self._connect() == False:
          break

  def close(self):
    try:
      self.client.close()
      self.client.disconnect()
    except:
      pass
